﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using JobSchedule.Extension;

namespace JobSchedule.Base
{
    public class ScheduleBase
    {
        private const string JobFile = "JobsConfig.json";
        private static readonly string JobNamespceFormat;
        public static readonly string ServiceName;
        private static readonly List<Jobdetail> JobList;

        static ScheduleBase()
        {
            var job = JobFile.JsonToObject<JobsConfig>();
            ServiceName = job.Quartz.ServiceName;
            JobNamespceFormat = job.Quartz.Namespace;
            JobList = job.Quartz.JobList;
        }

        private static IScheduler _scheduler;
        public static IScheduler Scheduler
        {
            get
            {
                if (_scheduler != null)
                {
                    return _scheduler;
                }
                var properties = new NameValueCollection();
                properties["quartz.scheduler.instanceName"] = "CUBE后台作业监控系统";

                // 设置线程池
                properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
                properties["quartz.threadPool.threadCount"] = "5";
                properties["quartz.threadPool.threadPriority"] = "Normal";

                // 远程输出配置
                properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
                properties["quartz.scheduler.exporter.port"] = "555";
                properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
                properties["quartz.scheduler.exporter.channelType"] = "tcp";

                var schedulerFactory = new StdSchedulerFactory(properties);
                _scheduler = schedulerFactory.GetScheduler().Result;
                return _scheduler;
            }
        }

        public static void InitScheduleJobs()
        {
            foreach (var job in JobList)
            {
                var jobdetail = JobBuilder.Create(Type.GetType(string.Format(JobNamespceFormat, job.JobName)))
                                           .WithIdentity(job.JobName, ServiceName)
                                           .Build();
                var trigger = TriggerBuilder.Create()
                     .WithCronSchedule(job.Cron)
                     .Build();
                Scheduler.ScheduleJob(jobdetail, trigger);

                Console.WriteLine($"任务 {string.Format(JobNamespceFormat, job.JobName)} 已完成调度装配");
            }

            Console.WriteLine("调度任务 初始化完毕");
        }
    }
}
